package org.spbsu.apco.common.serialization;

import org.springframework.stereotype.Component;

import java.io.*;

/**
 * User: solozobov
 * Date: 12.01.13
 */

@Component("javaSerializationMechanism")
public class JavaSerializationMechanismImpl implements SerializationMechanism {
    public byte[] serialize(final Object object) {
        try {
            final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            final ObjectOutputStream out = new ObjectOutputStream(bytes);
            out.writeObject(object);
            out.flush();
            bytes.flush();
            out.close();
            bytes.close();
            return bytes.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("Can't serialize Serializable object " + object.getClass().getName(), e);
        }
    }

    public Object deserialize(final byte[] representation) {
        try {
            final ByteArrayInputStream bytes = new ByteArrayInputStream(representation);
            final ObjectInputStream in = new ObjectInputStream(bytes);
            final Object result = in.readObject();
            in.close();
            bytes.close();
            return result;
        } catch (Exception e) {
            throw new RuntimeException("Can't deserialize Serializable object", e);
        }
    }
}
